package com.pocket.demo.core.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.pocket.demo.business.po.Role;
import io.jsonwebtoken.lang.Collections;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhaozhile
 */
public class RoleContext {
    private static final TransmittableThreadLocal<List<Role>> ACTIVE_ROLES_INHERITABLE_THREAD_LOCAL = new TransmittableThreadLocal();

    public static void setActiveRoles(List<Role> roles) {
        ACTIVE_ROLES_INHERITABLE_THREAD_LOCAL.set(roles);
    }

    public static List<Role> getActiveRoles() {
        List<Role> roles = ACTIVE_ROLES_INHERITABLE_THREAD_LOCAL.get();
        if (Collections.isEmpty(roles)) {
            return new ArrayList<>();
        }
        return roles;
    }

    public static List<Long> getActiveRoleIds() {
        return getActiveRoles().stream().map(Role::getRoleId).collect(Collectors.toList());
    }

    public static void remove() {
        ACTIVE_ROLES_INHERITABLE_THREAD_LOCAL.remove();
    }
}
